﻿#include "Scene0917.h"

cocos2d::Scene* Scene0917::createScene()
{
	return Scene0917::create();
}

bool Scene0917::init()
{
	if (!Scene::init())
	{
		return false;
	}

	//添加点击事件
	//事件监听器
	EventListenerTouchOneByOne* listenter = EventListenerTouchOneByOne::create();
	listenter->onTouchBegan = CC_CALLBACK_2(Scene0917::onTouchBegan, this);
	listenter->onTouchMoved = CC_CALLBACK_2(Scene0917::onTouchMoved, this);
	//吞没事件
	listenter->setSwallowTouches(true);

	//添加事件派发
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listenter, this);

	// 加载游戏页素材
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("plist/GameSence.plist", "plist/GameSence.png");

	Sprite *background = Sprite::create("Background.png");
	background->setPosition(Vec2(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2));
	addChild(background);

	char* name1 = CommonFunction::FontToUTF8("科职");
	// 自己
	player_self = new Player();
	player_self->account = name1;
	player_self->position = 3;
	loadPlayerUI(player_self);

	// 菜单

	MenuItemFont *leftItem = MenuItemFont::create(CommonFunction::FontToUTF8("左边添加玩家"), CC_CALLBACK_1(Scene0917::menuItemClicked, this));
	leftItem->setPosition(Vec2(-100, 0));
	leftItem->setTag(1);

	MenuItemFont *frontItem = MenuItemFont::create(CommonFunction::FontToUTF8("对面添加玩家"), CC_CALLBACK_1(Scene0917::menuItemClicked, this));
	frontItem->setPosition(Vec2(0, 50));
	frontItem->setTag(2);

	MenuItemFont *rightItem = MenuItemFont::create(CommonFunction::FontToUTF8("右边添加玩家"), CC_CALLBACK_1(Scene0917::menuItemClicked, this));
	rightItem->setPosition(Vec2(100, 0));
	rightItem->setTag(3);

	MenuItemFont *beginItem = MenuItemFont::create(CommonFunction::getChineseWithKey("begin game")->getCString(), CC_CALLBACK_1(Scene0917::beginGame, this));
	beginItem->setPosition(Vec2(0, -50));

	// 关闭按钮
	MenuItemImage *closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(Scene0917::menuItemClicked, this));
	closeItem->setTag(100);
	closeItem->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
	closeItem->setPosition(Vec2(-VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2));
	closeItem->setScale(2);

	//判断选牌类型按钮
	MenuItemFont*judgeItem = MenuItemFont::create(CommonFunction::getChineseWithKey("panduan")->getCString(), CC_CALLBACK_1(Scene0917::menuItemClicked, this));
	judgeItem->setTag(200);
	judgeItem->setVisible(false);

	Menu *menu = Menu::create(leftItem, frontItem, rightItem, closeItem, beginItem, judgeItem, NULL);
	menu->setTag(300);
	addChild(menu);

	//自动添加玩家并隐藏按钮
	menuItemClicked(leftItem);
	menuItemClicked(rightItem);
	menuItemClicked(frontItem);

	leftItem->setVisible(false);
	rightItem->setVisible(false);
	frontItem->setVisible(false);

	Button* showButton = Button::create("show_normal.png");
	showButton->setPosition(Vec2(VISIBLE_SIZE.width / 2 - 100, VISIBLE_SIZE.height / 2 - 40));
	showButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	showButton->setTag(100);
	showButton->setVisible(false);
	showButton->setScale(0.9);

	Button* unShowButton = Button::create("unShow_normal.png");
	unShowButton->setPosition(Vec2(VISIBLE_SIZE.width / 2 + 100, VISIBLE_SIZE.height / 2 - 40));
	unShowButton->addTouchEventListener(CC_CALLBACK_2(Scene0917::buttonClicked, this));
	unShowButton->setTag(200);
	unShowButton->setVisible(false);
	unShowButton->setScale(0.9);

	addChild(showButton);
	addChild(unShowButton);
	return true;
}

void Scene0917::beginGame(Ref *sender)
{

	//如果之前的game已经存在则初始化
	if (game)
	{
		//新的游戏开始把吧之前的牌的精灵清除
		game->selfCards_node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(game);

		player_self->node->removeChildByTag(2);
	}

	// 注意分析判断4个玩家是否都在，因为之后的操作基于各个玩家对象
	if (player_self && player_right && player_front && player_left)
	{
	}
	else
	{
		return;
	}
	// 1.洗牌
	int cards[54];
	game = new CardGame();
	game->gameDidBegan = true;
	game->shuffle(cards, 54);

	//测试牌型判断
	vector<int> arr(1, 1);
	PokerType Type = game->getPokerTypeWithCards(arr);

	// 2.发牌
	player_self->initCards();
	player_right->initCards();
	player_front->initCards();
	player_left->initCards();
	int start_pos = 3; // 先发给3号椅子的人
	Player *currentPlayer;
	for (int i = 0; i < 54; i++)
	{
		char pos_char = getPlayerCharPosition((start_pos + i - 1) % 4 + 1);

		// ♥️3
		if (cards[i] == 41)
		{
			game->first = pos_char;
		}
		// ♦️10
		if (cards[i] == 22)
		{
			game->red10_fk = pos_char;
		}
		// ♥️10
		if (cards[i] == 48)
		{
			game->red10_hx = pos_char;
		}

		// 把当前遍历的牌给到对应的玩家
		if (pos_char == 's')
		{
			currentPlayer = player_self;
		}
		else if (pos_char == 'l')
		{
			currentPlayer = player_left;
		}
		else if (pos_char == 'f')
		{
			currentPlayer = player_front;
		}
		else if (pos_char == 'r')
		{
			currentPlayer = player_right;
		}
		currentPlayer->cards[i / 4] = cards[i];
	}
	//发牌结束
	if (game->red10_fk == 's' || game->red10_hx == 's')
	{
		//显示晒红十按钮
		this->getChildByTag(100)->setVisible(true);
		this->getChildByTag(200)->setVisible(true);
	}
	else
	{
		//隐藏晒红十按钮
		this->getChildByTag(100)->setVisible(false);
		this->getChildByTag(200)->setVisible(false);

		//找到选牌按钮，并显示
		getChildByTag(300)->getChildByTag(200)->setVisible(true);
	}

	// 3.展现自己的牌

	// 排序
	player_self->sortCards();

	int count = player_self->countCards();
	int mid = count / 2;

	float midX = (VISIBLE_SIZE.width - 180) / 2;

	// 显示
	for (int i = 0; i < player_self->countCards(); i++)
	{
		Sprite* cardSprite = game->getCardspriteWithCardValue(player_self->cards[i]);

		cardSprite->setScale(0.8);

		cardSprite->setPosition(Vec2(midX + 45 * (i - mid) + (count % 2 == 0 ? 30 : 0) + 160, VISIBLE_SIZE.height / 2 - 200));

		cardsOriginY = cardSprite->getPositionY();

		game->selfCards_node->addChild(cardSprite);

	}
	addChild(game->selfCards_node);
}

bool Scene0917::onTouchBegan(Touch* touch, Event* event)
{
	Vec2 point = touch->getLocation();
	//前提：自己的牌显示出来了
	//短逻辑
	if (!game || !game->gameDidBegan)
	{
		return true;
	}
	int count = player_self->countCards();
	bool didTouchCard = false;//是否点到牌
							  //遍历每张牌
	for (int i = 0; i < count; i++)//通过牌的值来获取牌的精灵
	{
		Node* card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点所占区域
		Rect rect = card_node->getBoundingBox();

		//计算实际点击区域（除了最后一张，其他的宽度改为牌与牌的间距）
		Rect touchRect = Rect(rect.origin.x, rect.origin.y,
			(i == count - 1 ? rect.size.width : 50), rect.size.height);

		//判断该区域是否包含了我点击的区域
		if (touchRect.containsPoint(point))
		{
			if (card_node->getPositionY() == cardsOriginY)
			{
				//弹出
				card_node->setPositionY(cardsOriginY + 50);
			}
			else
			{
				//缩进
				card_node->setPositionY(cardsOriginY);
			}
			didTouchCard = true;
			break;
		}
	}
	if (didTouchCard == false)
	{
		//把牌归位
		for (int i = 0; i < count; i++)
		{
			Node* card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			card_node->setPositionY(cardsOriginY);
		}

	}
	return true;
}

void Scene0917::onTouchMoved(Touch* touch, Event* event)
{
	Vec2 point = touch->getLocation();

	Vec2 start_location = touch->getStartLocation();

	if (std::abs(point.x - start_location.x)<50)
	{
		return;
	}
	//前提：自己的牌显示出来了
	//短逻辑
	if (!game || !game->gameDidBegan)
	{
		return;
	}
	int count = player_self->countCards();
	//遍历每张牌
	for (int i = 0; i < count; i++)//通过牌的值来获取牌的精灵
	{
		Node* card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点所占区域
		Rect rect = card_node->getBoundingBox();

		//计算实际点击区域（除了最后一张，其他的宽度改为牌与牌的间距）
		Rect touchRect = Rect(rect.origin.x, rect.origin.y,
			(i == count - 1 ? rect.size.width : 50), rect.size.height);

		//判断该区域是否包含了我点击的区域
		if (touchRect.containsPoint(point))
		{
			if (card_node->getPositionY() == cardsOriginY)
			{
				card_node->setPositionY(cardsOriginY + 50);
			}
		}
	}
}

void Scene0917::buttonClicked(Ref* sender, Widget::TouchEventType type)
{
	if (type == Widget::TouchEventType::ENDED)
	{
		int res = 0;
		Button* btn = (Button*)sender;
		switch (btn->getTag())
		{
		case 100://晒
		{
			if (game->red10_fk == 's'&&game->red10_hx == 's')
			{
				res = 3;
			}
			else if (game->red10_fk == 's')
			{
				res = 1;
			}
			else if (game->red10_hx == 's')
			{
				res = 2;
			}
			player_self->show(res);
			/*player_left->show(res);
			player_right->show(res);
			player_front->show(res);*/
			break;
		}
		case 200://不晒

			break;
		default:
			break;
		}
		this->getChildByTag(100)->setVisible(false);
		this->getChildByTag(200)->setVisible(false);

		//找到选牌按钮，并显示
		getChildByTag(300)->getChildByTag(200)->setVisible(true);
	}
}

void Scene0917::setRoomId(int roomId)
{
	Label *label = Label::createWithSystemFont(StringUtils::format("%s%d", CommonFunction::getChineseWithKey("a")->getCString(), roomId), "Arial", 50);
	label->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT);
	label->setPosition(Vec2(VISIBLE_SIZE.width, VISIBLE_SIZE.height));
	addChild(label);
}

void Scene0917::menuItemClicked(Ref *sender)
{
	MenuItemFont *item = (MenuItemFont *)sender;
	char* str6 = CommonFunction::FontToUTF8("右边删除玩家");
	switch (item->getTag())
	{
	case 1: {// 在左侧添加玩家
		player_left = new Player();
		player_left->account = CommonFunction::FontToUTF8("左边");
		player_left->position = 2;
		loadPlayerUI(player_left);

		item->setString(CommonFunction::FontToUTF8("左边删除玩家"));
		item->setTag(4);
		break;
	}
	case 2:
	{// 在对面添加玩家
		player_front = new Player();
		player_front->account = CommonFunction::FontToUTF8("对面");
		player_front->position = 1;
		loadPlayerUI(player_front);

		item->setString(CommonFunction::FontToUTF8("对面删除玩家"));
		item->setTag(5);
		break;
	}
	case 3:
	{// 在右侧添加玩家
		player_right = new Player();
		player_right->account = CommonFunction::FontToUTF8("右边");
		player_right->position = 4;
		loadPlayerUI(player_right);

		item->setString(CommonFunction::FontToUTF8("右边删除玩家"));
		item->setTag(6);
		break;
	}
	case 4:
	{// 从左侧移除玩家
		player_left->node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(player_left);

		item->setString(CommonFunction::FontToUTF8("左边添加玩家"));
		item->setTag(1);
		break;
	}
	case 5:
	{// 从对面移除玩家
		player_front->node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(player_front);

		item->setString(CommonFunction::FontToUTF8("对面添加玩家"));
		item->setTag(2);
		break;
	}
	case 6:
	{// 从右侧移除玩家
		player_right->node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(player_right);

		item->setString(CommonFunction::FontToUTF8("右边添加玩家"));
		item->setTag(3);
		break;
	}
	case 200://判断选牌类型按钮
	{
		//获取我选择了哪些牌(遍历自己的牌，找出弹出的牌）
		vector<int> arr;
		for (int i = 0; i < player_self->countCards(); i++)
		{
			Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			if(card_node->getPositionY()>cardsOriginY)
				{
					arr.push_back(player_self->cards[i]);
				}
		}
		PokerType type = game->getPokerTypeWithCards(arr);
		switch (type)
		{
		case POKER_TYPE_SINGLE:
			break;
		case POKER_TYPE_DOUBLE:
			break;
		case POKER_TYPE_KING_BOMB:
			break;
		case POKER_TYPE_REDTEN_BOMB:
			break;
		case POKER_TYPE_THREE_BOMB:
			break;
		case POKER_TYPE_FOUR_BOMB:
			break;
		case POKER_TYPE_STRAIGHT:
			break;
		default:
			break;
		}
		break;
	}
	default:
		Director::getInstance()->replaceScene(Scene0910::createScene());
		break;
	}
}

char Scene0917::getPlayerCharPosition(int pos)
{
	if (player_self->position == 1)
	{
		if (pos == 2) return 'r';
		if (pos == 3) return 'f';
		if (pos == 4) return 'l';
	}
	else if (player_self->position == 2)
	{
		if (pos == 1) return 'l';
		if (pos == 3) return 'r';
		if (pos == 4) return 'f';
	}
	else if (player_self->position == 3)
	{
		if (pos == 1) return 'f';
		if (pos == 2) return 'l';
		if (pos == 4) return 'r';
	}
	else if (player_self->position == 4)
	{
		if (pos == 1) return 'r';
		if (pos == 2) return 'f';
		if (pos == 3) return 'l';
	}
	return 's';
}

void Scene0917::loadPlayerUI(Player *player)
{
	// 把椅子号转换成具体位置
	player->pos_char = getPlayerCharPosition(player->position);

	player->createPlayerNode();
	addChild(player->node);
}